import tkinter as tk
from tkinter import ttk, messagebox

from iotdb.Session import Session

# IoTDB 连接配置
ip = ""
port_ = ""
username_ = ""
password_ = ""

session = None


def connect_to_iotdb():
    global session, ip, port_, username_, password_
    ip = ip_entry.get()
    port_ = port_entry.get()
    username_ = username_entry.get()
    password_ = password_entry.get()

    try:
        session = Session(ip, port_, username_, password_)
        session.open(False)
        messagebox.showinfo("连接成功", "已成功连接到 IoTDB")
        load_databases()
    except Exception as e:
        messagebox.showerror("连接失败", f"连接到 IoTDB 时出错: {str(e)}")


def load_databases():
    try:
        result = session.execute_query_statement("show databases")
        data_list = []
        while result.has_next():
            row = result.next()
            data_list.append(row.get_fields()[0].value.decode('utf8'))

        database_listbox.delete(0, tk.END)
        for db in data_list:
            database_listbox.insert(tk.END, db)
    except Exception as e:
        messagebox.showerror("加载数据库失败", f"加载数据库时出错: {str(e)}")
        print(f"加载数据库时出错: {str(e)}")


def on_database_select(event):
    selected_db = database_listbox.get(tk.ANCHOR)
    load_timeseries(selected_db)


def load_timeseries(database):
    try:
        result = session.execute_query_statement("show timeseries")
        data_list = []
        while result.has_next():
            row = result.next()
            column = row.get_fields()[0].value.decode('utf8')
            if column.startswith(database):
                data_list.append(column)

        table_listbox.delete(0, tk.END)
        for ts in data_list:
            print(ts)
            table_listbox.insert(tk.END, ts)
    except Exception as e:
        messagebox.showerror("加载 TimeSeries 失败", f"加载 TimeSeries 时出错: {str(e)}")


def on_table_select(event):
    selected_table = table_listbox.get(tk.ANCHOR)
    # 你可以在这里添加更多操作，例如加载表的详细信息
    pass


def execute_query():
    try:
        query = query_entry.get()
        result = session.execute_query_statement(query)

        # 获取列名
        column_names = result.get_column_names()

        # 清空现有的列和数据
        data_tree.delete(*data_tree.get_children())
        data_tree["columns"] = column_names
        data_tree["show"] = "headings"

        # 设置列名
        for col in column_names:
            data_tree.heading(col, text=col)
            data_tree.column(col, width=len(col) * 5)  # 根据需要调整列宽

        # 填充数据
        while result.has_next():
            row = result.next()
            fields = [field.value.decode('utf8') if isinstance(field.value, bytes) else field.value for field in
                      row.get_fields()]
            data_tree.insert("", tk.END, values=[row.get_timestamp()] + fields)

    except Exception as e:
        messagebox.showerror("执行查询失败", f"执行查询时出错: {str(e)}")


# 创建主窗口
root = tk.Tk()
root.title("IoTDB 连接器")
root.geometry("1000x800")

# 连接信息输入框
ip_label = tk.Label(root, text="IP 地址")
ip_label.grid(row=0, column=0, padx=10, pady=5)
ip_entry = tk.Entry(root, )
ip_entry.grid(row=0, column=1, padx=10, pady=5)
ip_entry.insert(0, "10.6.103.210")

port_label = tk.Label(root, text="端口")
port_label.grid(row=1, column=0, padx=10, pady=5)
port_entry = tk.Entry(root)
port_entry.grid(row=1, column=1, padx=10, pady=5)
port_entry.insert(0, "6667")

username_label = tk.Label(root, text="用户名")
username_label.grid(row=2, column=0, padx=10, pady=5)
username_entry = tk.Entry(root)
username_entry.grid(row=2, column=1, padx=10, pady=5)
username_entry.insert(0, "root")

password_label = tk.Label(root, text="密码")
password_label.grid(row=3, column=0, padx=10, pady=5)
password_entry = tk.Entry(root, show="*")
password_entry.grid(row=3, column=1, padx=10, pady=5)
password_entry.insert(0, "root")

# 连接按钮
connect_button = tk.Button(root, text="连接到 IoTDB", command=connect_to_iotdb)
connect_button.grid(row=4, column=0, columnspan=2, pady=10)

# 数据库列表框
database_label = tk.Label(root, text="数据库")
database_label.grid(row=5, column=0, padx=10, pady=5)
database_listbox = tk.Listbox(root, height=10)
database_listbox.grid(row=6, column=0, padx=10, pady=5)
database_listbox.bind('<<ListboxSelect>>', on_database_select)

# TimeSeries 列表框
table_label = tk.Label(root, text="TimeSeries")
table_label.grid(row=5, column=1, padx=20, pady=5)
table_listbox = tk.Listbox(root, height=10, width=60)  # 增加宽度
table_listbox.grid(row=6, column=1, padx=20, pady=5)
table_listbox.bind('<<ListboxSelect>>', on_table_select)

# SQL 查询输入框
query_label = tk.Label(root, text="SQL 查询")
query_label.grid(row=7, column=0, columnspan=2, padx=10, pady=5)
query_entry = tk.Entry(root, width=80)
query_entry.grid(row=8, column=0, columnspan=2, padx=10, pady=5)

# 查询按钮
query_button = tk.Button(root, text="执行查询", command=execute_query)
query_button.grid(row=9, column=0, columnspan=2, pady=10)

# 数据展示树形视图
data_label = tk.Label(root, text="数据")
data_label.grid(row=10, column=0, columnspan=2, padx=10, pady=5)
columns = ("Field1", "Field2", "Field3", "Field4", "Field5", "Field6", "Field7", "Field8")  # 根据实际情况调整列名
data_tree = ttk.Treeview(root, columns=columns, show="headings")
for col in columns:
    data_tree.heading(col, text=col)
data_tree.grid(row=11, column=0, columnspan=2, padx=10, pady=5, sticky="nsew")

# 配置网格权重
root.grid_rowconfigure(11, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)

# 运行主循环
root.mainloop()
